package com.exsun.ex1077.ui.activity.vehicledetail

import android.os.Bundle
import androidx.lifecycle.viewModelScope
import com.exsun.ex1077.R
import com.exsun.ex1077.databinding.ActivityVehicleDetailBinding
import com.exsun.ex1077.network.entity.MapVehicle
import com.exsun.ex1077.ui.fragment.vehicleinfo.VehicleInfoFragment
import com.exsun.ex1077.ui.fragment.vehicletrack.VehicleTrackFragment
import com.exsun.ex1077.ui.fragment.vehiclevideo.VehicleVideoFragment
import com.exsun.ex1077.ui.popup.TimeSelectPopup
import com.lxj.xpopup.XPopup
import com.zhangping.fastjetpack.base.BaseActivity
import com.zhangping.fastjetpack.base.BaseFragment
import com.zhangping.fastjetpack.callback.TwoCallback
import com.zhangping.fastjetpack.extend.*
import com.zhangping.fastjetpack.network.websocket.WebSocketManager
import kotlinx.android.synthetic.main.action_bar.*
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_vehicle_detail.*
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import xyz.doikki.videoplayer.player.VideoViewManager
import java.util.*

/**
 * 描述：车辆详情
 * 作者：ZhangPing
 * 创建时间：2022/8/10 10:38
 */
class VehicleDetailActivity: BaseActivity<VehicleDetailViewModel, ActivityVehicleDetailBinding>() {

    private var infoFragment = VehicleInfoFragment()
    private var trackFragment = VehicleTrackFragment()
    private var videoFragment = VehicleVideoFragment()
    private val fragmentList = arrayListOf(infoFragment, trackFragment, videoFragment)
    private lateinit var timeSelectPopup: TimeSelectPopup

    override fun backFragment(): BaseFragment<*, *> = videoFragment

    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.vm = mViewModel
        super.initView(savedInstanceState)
        mViewModel.apply {
            model.set(intent.getSerializableExtra("model") as MapVehicle?)
            title.set(model.get()!!.vehicleNo)
            infoFragment.arguments = Bundle().apply {
                putSerializable("model", model.get())
            }
            trackFragment.arguments = Bundle().apply {
                putSerializable("model", model.get())
            }
            videoFragment.arguments = Bundle().apply {
                putSerializable("model", model.get())
            }
        }
        infoPage.setOnClickListener {
            if (mViewModel.pageType.get() == 0) return@setOnClickListener
            mViewModel.pageType.set(0)
            showFragment(fragmentList, 0)
        }
        trackPage.setOnClickListener {
            if (mViewModel.pageType.get() == 1) return@setOnClickListener
            mViewModel.pageType.set(1)
            showFragment(fragmentList, 1)
        }
        videoPage.setOnClickListener {
            if (mViewModel.pageType.get() == 2) return@setOnClickListener
            mViewModel.pageType.set(2)
            showFragment(fragmentList, 2)
        }
        timeSelectPopup = XPopup.Builder(this)
            .asCustom(TimeSelectPopup(this, object : TwoCallback<Date, Date>{
                override fun onCall(startTime: Date, endTime: Date) {
                    infoFragment.loadMileageData(startTime.toDateStr(with000000 = true), endTime.toDateStr(with235959 = true))
                }
            })) as TimeSelectPopup
        timeAction.setOnClickListener {
            timeSelectPopup.show()
        }
        setupFragment(R.id.frame, fragmentList)
        if (intent.getBooleanExtra("videoFirst", false)){
            mViewModel.pageType.set(2)
            showFragment(fragmentList, 2)
        }else{
            showFragment(fragmentList, 0)
        }
    }

    override fun createObserver() {
        super.createObserver()
        WebSocketManager.apply {
            connectStateLiveData.observeInActivity(this@VehicleDetailActivity){
                when (it){
                    STATE_OPEN -> {
                        startVehicleTrackFromSocket()
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
        startVehicleTrackFromSocket()
    }

    override fun onStop() {
        stopSocket()
        super.onStop()
    }

    /**
     * 开始从Socket读取车辆信息
     */
    private fun startVehicleTrackFromSocket(){
        mViewModel.viewModelScope.launch {
            delay(1000)
            mViewModel.model.get()?.dvo?.let {
                WebSocketManager.sendMsg("type=2&dvo=${it}")
            }
        }
    }

    /**
     * 停止从Socket获取信息
     */
    private fun stopSocket(){
        WebSocketManager.sendMsg("type=2&dvo=0")
    }

}